﻿using AleaBelli.Core.Data;
using AleaBelli.Core.Service;
using AleaBelli.Core.Util;
using AleaBelli.Model;
using AleaBelli.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace AleaBelli
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private static readonly Logger log = Logger.Instance;

        public MainWindow()
        {
            InitializeComponent();

            // set up the service
            Model.Service = new GameServiceImpl();

            log.Info("MainWindow - InitializeComponent " + Model.Name);
            InitMap();
        }

        private void InitMap()
        {
            // pull the map from the server
            Hex[,] hexmap = Model.Service.GetMap();

            // create the model object this hex
            int width = hexmap.GetUpperBound(0);
            int height = hexmap.GetUpperBound(1);

            // Use for-loops to iterate over the array elements.
            for (int x = 0; x <= width; x++)
            {
                for (int y = 0; y <= height; y++)
                {
                    Hex hex = hexmap[x, y];

                    ModelHex modelHex = new ModelHex { Hex = hex };
                    modelHex.Terrain = new ImageBrush(ImageHelper.LoadBitmapFromResource("/Resources/Images/sea01.png"));

                    // add the hexes
                    HexUserControl hux = new HexUserControl();
                    hux.Width = ModelHex.HEX_WIDTH;
                    hux.Height = ModelHex.HEX_HEIGHT;
                    hux.DataContext = modelHex;

                    int screenx = x * 100;
                    int screeny = y * ModelHex.HEX_HEIGHT;
                    hux.Margin = new Thickness(screenx, screeny, 0, 0);

                    // add the click handler
                    hux.MouseUp += hux_MouseUp;

                    this.MapCanvas.Children.Add(hux);
                }
            }
        }

        void hux_MouseUp(object sender, MouseButtonEventArgs e)
        {
            HexUserControl hux = sender as HexUserControl;
            Model.OnMouseUp(hux.DataContext as ModelHex);
        }

        public Model.GameViewModel Model
        {
            get
            {
                return this.DataContext as Model.GameViewModel;
            }
        }
    }
}
